const express = require('express');
const cors = require('cors');
const mysql = require('mysql2');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

const app = express();
const port = 3001;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 数据库连接配置
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'travel_diary',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 登录接口
app.post('/api/login', async (req, res) => {
  const { username, password } = req.body;
  console.log('登录请求:', { username, password });

  try {
    const [rows] = await pool.promise().query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );
    console.log('查询结果:', rows);

    if (rows.length === 0) {
      return res.json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    const user = rows[0];
    console.log('找到用户:', user);

    // 直接比较密码
    if (password !== user.password) {
      console.log('密码不匹配:', { input: password, stored: user.password });
      return res.json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    console.log('登录成功，用户信息:', user);
    res.json({
      success: true,
      message: '登录成功',
      user: {
        id: user.id,
        username: user.username,
        nickname: user.nickname || user.username
      }
    });
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败'
    });
  }
});

// 注册接口
app.post('/api/register', async (req, res) => {
  const { username, password, nickname } = req.body;
  console.log('注册请求:', { username, password, nickname });

  try {
    // 检查用户名是否已存在
    const [existingUsers] = await pool.promise().query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );

    if (existingUsers.length > 0) {
      return res.json({
        success: false,
        message: '用户名已存在'
      });
    }

    // 直接使用明文密码
    const [result] = await pool.promise().query(
      'INSERT INTO users (username, password, nickname) VALUES (?, ?, ?)',
      [username, password, nickname]
    );

    res.json({
      success: true,
      message: '注册成功',
      user: {
        id: result.insertId,
        username,
        nickname
      }
    });
  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({
      success: false,
      message: '注册失败'
    });
  }
});

// 获取日记列表
app.get('/api/diaries', async (req, res) => {
  const user_id = req.query.user_id;
  console.log('获取日记列表，用户ID:', user_id);

  try {
    let sql = `
      SELECT d.*, u.username, u.nickname 
      FROM diaries d 
      LEFT JOIN users u ON d.user_id = u.id 
    `;
    const params = [];

    // 如果提供了用户ID，只返回该用户的日记
    if (user_id) {
      sql += ' WHERE d.user_id = ?';
      params.push(user_id);
    }

    sql += ' ORDER BY d.created_at DESC';

    const [diaries] = await pool.promise().query(sql, params);
    console.log('查询到的日记:', diaries);
    res.json({
      success: true,
      data: diaries
    });
  } catch (error) {
    console.error('获取日记列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取日记列表失败'
    });
  }
});

// 创建日记
app.post('/api/diaries', async (req, res) => {
  console.log('收到新增日记请求:', req.body);
  const { user_id, title, content, location, weather, mood, date } = req.body;
  
  // 参数验证
  if (!user_id || !title || !content) {
    console.log('参数验证失败:', { user_id, title, content });
    return res.status(400).json({
      success: false,
      message: 'user_id、title、content 不能为空'
    });
  }

  try {
    // 检查用户是否存在
    const [users] = await pool.promise().query(
      'SELECT * FROM users WHERE id = ?',
      [user_id]
    );
    console.log('查询用户结果:', users);

    if (users.length === 0) {
      console.log('用户不存在:', user_id);
      return res.status(400).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 插入日记
    const [result] = await pool.promise().query(
      'INSERT INTO diaries (user_id, title, content, location, weather, mood, date) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [user_id, title, content, location || '', weather || '', mood || '', date || new Date().toISOString().split('T')[0]]
    );
    console.log('插入日记结果:', result);

    if (!result || !result.insertId) {
      console.error('插入日记失败: 没有返回insertId');
      return res.status(500).json({
        success: false,
        message: '创建日记失败: 数据库操作异常'
      });
    }

    res.json({
      success: true,
      message: '日记创建成功',
      diary_id: result.insertId
    });
  } catch (error) {
    console.error('创建日记失败:', error);
    // 检查是否是数据库连接错误
    if (error.code === 'ECONNREFUSED') {
      return res.status(500).json({
        success: false,
        message: '数据库连接失败，请检查数据库服务是否正常运行'
      });
    }
    // 检查是否是SQL语法错误
    if (error.code === 'ER_PARSE_ERROR') {
      return res.status(500).json({
        success: false,
        message: '数据库操作失败: SQL语法错误'
      });
    }
    res.status(500).json({
      success: false,
      message: '创建日记失败: ' + error.message
    });
  }
});

// 获取单个日记详情
app.get('/api/diaries/:id', async (req, res) => {
  const id = req.params.id;
  console.log('获取日记详情，ID:', id);

  try {
    const [rows] = await pool.promise().query(
      'SELECT * FROM diaries WHERE id = ?',
      [id]
    );

    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '日记不存在'
      });
    }

    const diary = rows[0];
    
    // 处理图片数据
    let images = [];
    if (diary.images) {
      try {
        if (typeof diary.images === 'string') {
          if (diary.images.startsWith('[') || diary.images.startsWith('{')) {
            images = JSON.parse(diary.images);
          } else {
            images = [diary.images];
          }
        } else if (Array.isArray(diary.images)) {
          images = diary.images;
        }
      } catch (e) {
        console.error('解析图片数据失败:', e);
        images = [diary.images];
      }
    }

    res.json({
      success: true,
      data: {
        ...diary,
        images
      }
    });
  } catch (error) {
    console.error('获取日记详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取日记详情失败'
    });
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在端口 ${port}`);
}); 